﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JiebaNet.Segmenter;
using Mvvm.Models;
using MVVM.Services;

namespace Mvvm.Services;

class ChatDataProcessService
{
    private readonly EmotionalAnalysisService _emotionalAnalysisService = new EmotionalAnalysisService();
    
    private readonly ChatTimeReportService _chatTimeReportService = new ChatTimeReportService();
    public  string PrintProcessedservice(ChatProcessedData chatProcessedData)
    {
        // 控制台输出chatProcessedData内的数据
        Console.WriteLine("聊天数据处理结果：");
        Console.WriteLine("聊天总数："+chatProcessedData.TotalChatCount);
        Console.WriteLine("聊天总字数："+chatProcessedData.TotalWordCount);
        Console.WriteLine("用户1是："+chatProcessedData.Username1);
        Console.WriteLine("用户2是："+chatProcessedData.Username2);
        Console.WriteLine("用户1发送了"+chatProcessedData.User1MessageCount+"条消息，用户2发送了"+chatProcessedData.User2MessageCount+"条消息");
        Console.WriteLine("用户1发送了"+chatProcessedData.User1WordCount+"个词，用户2发送了"+chatProcessedData.User2WordCount+"个词");
        // 控制台输出高频词及其频数
        Console.WriteLine("---------用户1高频词及其频数：---------");
        Console.WriteLine(chatProcessedData.User1HighFrequencyWords);
        Console.WriteLine("---------用户2高频词及其频数：---------");
        Console.WriteLine(chatProcessedData.User2HighFrequencyWords);
        
        // 输出情感相关数据
        Console.WriteLine("\n---------用户情绪分析：---------\n");
        Console.WriteLine("积极情绪消息：");
        Console.WriteLine("  - 总数：" + chatProcessedData.PositiveMessageCount);
        Console.WriteLine("  - 包含：");
        Console.WriteLine("    - 喜爱情绪消息数量：" + chatProcessedData.LoveMessageCount);
        Console.WriteLine("    - 愉快情绪消息数量：" + chatProcessedData.HappyMessageCount);

        Console.WriteLine("\n中性情绪消息数量：" + chatProcessedData.NeutralMessageCount);
        
        Console.WriteLine("\n消极情绪消息：");
        Console.WriteLine("  - 总数：" + chatProcessedData.NegativeMessageCount);
        Console.WriteLine("  - 包含：");
        Console.WriteLine("    - 愤怒情绪消息数量：" + chatProcessedData.AngryMessageCount);
        Console.WriteLine("    - 厌恶情绪消息数量：" + chatProcessedData.DisgustMessageCount);
        Console.WriteLine("    - 恐惧情绪消息数量：" + chatProcessedData.FearMessageCount);
        Console.WriteLine("    - 悲伤情绪消息数量：" + chatProcessedData.SadMessageCount);
        
        Console.WriteLine("\n用户 1 情绪消息：");
        Console.WriteLine("  - 积极消息数量：" + chatProcessedData.User1PositiveMessageCount);
        Console.WriteLine("  - 中性消息数量：" + chatProcessedData.User1NeutralMessageCount);
        Console.WriteLine("  - 消极消息数量：" + chatProcessedData.User1NegativeMessageCount);
        
        Console.WriteLine("\n用户 2 情绪消息：");
        Console.WriteLine("  - 积极消息数量：" + chatProcessedData.User2PositiveMessageCount);
        Console.WriteLine("  - 中性消息数量：" + chatProcessedData.User2NeutralMessageCount);
        Console.WriteLine("  - 消极消息数量：" + chatProcessedData.User2NegativeMessageCount);
        
       
        // 将控制台的输出拼接成字符串，包括高频词
        string result = "聊天数据处理结果：\n" +
            "聊天总数：" + chatProcessedData.TotalChatCount + "\n" +
            "聊天总字数：" + chatProcessedData.TotalWordCount + "\n" +
            "用户1是：" + chatProcessedData.Username1 + "\n" +
            "用户2是：" + chatProcessedData.Username2 + "\n" +
            "用户1发送了" + chatProcessedData.User1MessageCount + "条消息，用户2发送了" + chatProcessedData.User2MessageCount +
            "\n" +
            "条消息，用户1发送了" + chatProcessedData.User1WordCount + "个词，用户2发送了" + chatProcessedData.User2WordCount + "个词"+
            "\n---------用户1高频词及其频数：---------\n";
        
            result += chatProcessedData.User1HighFrequencyWords;
        
            result += "\n---------用户2高频词及其频数：---------\n";
        
            result += chatProcessedData.User2HighFrequencyWords;
            
            result+= "\n---------用户情绪分析：---------\n"+
                    "积极情绪消息：\n"+
                    "  - 总数：" + chatProcessedData.PositiveMessageCount + "\n" +
                    "  - 包含：\n" +
                    "    - 喜爱情绪消息数量：" + chatProcessedData.LoveMessageCount + "\n" +
                    "    - 愉快情绪消息数量：" + chatProcessedData.HappyMessageCount + "\n" +
                    "中性情绪消息数量：" + chatProcessedData.NeutralMessageCount + "\n" +
                    "消极情绪消息：\n" +
                    "  - 总数：" + chatProcessedData.NegativeMessageCount + "\n" +
                    "  - 包含：\n" +
                    "    - 愤怒情绪消息数量：" + chatProcessedData.AngryMessageCount + "\n" +
                    "    - 厌恶情绪消息数量：" + chatProcessedData.DisgustMessageCount + "\n" +
                    "    - 恐惧情绪消息数量：" + chatProcessedData.FearMessageCount + "\n" +
                    "    - 悲伤情绪消息数量：" + chatProcessedData.SadMessageCount + "\n" +
                    "用户 1 情绪消息：\n" +
                    "  - 积极消息数量：" + chatProcessedData.User1PositiveMessageCount + "\n" +
                    "  - 中性消息数量：" + chatProcessedData.User1NeutralMessageCount + "\n" +
                    "  - 消极消息数量：" + chatProcessedData.User1NegativeMessageCount + "\n" +
                    "用户 2 情绪消息：\n" +
                    "  - 积极消息数量：" + chatProcessedData.User2PositiveMessageCount + "\n" +
                    "  - 中性消息数量：" + chatProcessedData.User2NeutralMessageCount + "\n" +
                    "  - 消极消息数量：" + chatProcessedData.User2NegativeMessageCount + "\n";
        
        return result;
    }

    // 解析聊天记录
    public List<ChatData> ParseChatLog(string chatLog)
    {
        //处理字符串，在每个换行符/n前加一个/r
        chatLog = chatLog.Replace("\n", "\r\n");
        // 获取当前日期
        var today = DateTime.Today;
        var todayDateString = today.ToString("yyyy/MM/dd");
        var lines = chatLog.Split([Environment.NewLine], StringSplitOptions.RemoveEmptyEntries);
        var specificStarts = new[] { "对方已成功接收了你发送的离线文件", "你已下载文件", "发起了屏幕分享", "请使用最新版手机QQ体验新功能" };
        lines = specificStarts.Aggregate(lines, (current, start) => current.Where(l => !l.StartsWith(start)).ToArray());

        var chatDataList = new List<ChatData>();
        string? currentUser = null;
        DateTime? currentTimestamp = null;
        var currentMessage = "";
        var userNameList = new List<string>();

        foreach (var line in lines)
        {
            var trimmedLine = line.Trim();
            string?[] parts3 = trimmedLine.Split([' '], 3);
            // QQ消息包含时间，这个if用来处理QQ聊天记录
            if (trimmedLine.Contains(' ') && trimmedLine.Contains(':') && parts3.Length is 2 or 3 && parts3[1].Length is 8 or 9 or 10)
            {
                string?[] parts = trimmedLine.Split([' '], 3);
                var newCurrentUser = parts[0];
                if (!userNameList.Contains(newCurrentUser))
                {
                    userNameList.Add(newCurrentUser);
                }

                if (parts.Length == 2)
                {
                    var timestamp = parts[1];
                    parts = new string[] { parts[0], todayDateString, timestamp };
                }
                var newCurrentTimestamp = parts[1] + " " + parts[2];

                if (DateTime.TryParse(newCurrentTimestamp, out var parsedTimestamp))
                {
                    if (currentUser != newCurrentUser || currentTimestamp != parsedTimestamp)
                    {
                        if (currentUser != null && currentTimestamp != null)
                        {
                            var cleanedMessage = string.Join("\n", currentMessage.Split('\n').Where(s => !string.IsNullOrWhiteSpace(s)));
                            chatDataList.Add(new ChatData
                            {
                                Username = currentUser,
                                Timestamp = currentTimestamp.Value,
                                Content = cleanedMessage,
                                Type = string.IsNullOrWhiteSpace(cleanedMessage) ? "Others" : "String"
                            });
                        }

                        currentUser = newCurrentUser;
                        currentTimestamp = parsedTimestamp;
                        currentMessage = "";
                    }
                }
            }
            // 微信消息不包含时间，这个if用来处理微信聊天记录
            else if (trimmedLine.EndsWith($":") && parts3[0].Length < 30 && parts3[0].Length > 1)
            {
                string?[] parts = trimmedLine.Split([':'], 2);
                var newCurrentUser = parts[0];
                if (!userNameList.Contains(newCurrentUser))
                {
                    userNameList.Add(newCurrentUser);
                }

                if (currentUser != newCurrentUser)
                {
                    if (currentUser != null && currentTimestamp != null)
                    {
                        var cleanedMessage = string.Join("\n", currentMessage.Split('\n').Where(s => !string.IsNullOrWhiteSpace(s)));
                        chatDataList.Add(new ChatData
                        {
                            Username = currentUser,
                            Timestamp = currentTimestamp.Value, // 或者设置为null或其他默认值
                            Content = cleanedMessage,
                            Type = string.IsNullOrWhiteSpace(cleanedMessage) ? "Others" : "String"
                        });
                    }

                    currentUser = newCurrentUser;
                    currentTimestamp = null; // 设置为null或其他默认值
                    currentMessage = "";
                }
                
            }
            else if (!string.IsNullOrWhiteSpace(trimmedLine))
            {
                //增加需要被替换的情况
                trimmedLine = trimmedLine.Replace("[图片]", "");
                trimmedLine = trimmedLine.Replace("[动画表情]", "");
                trimmedLine = trimmedLine.Replace("请使用最新版手机QQ体验新功能", "");
                if (currentMessage.Length > 0)
                {
                    currentMessage += "\n";
                }
                currentMessage += trimmedLine;
            }
        }

        if (currentUser != null && currentTimestamp != null)
        {
            var cleanedMessage = string.Join("\n", currentMessage.Split('\n').Where(s => !string.IsNullOrWhiteSpace(s)));
            chatDataList.Add(new ChatData
            {
                Username = currentUser,
                Timestamp = currentTimestamp.Value,
                Content = cleanedMessage,
                Type = string.IsNullOrWhiteSpace(cleanedMessage) ? "Others" : "String"
            });
        }

        return chatDataList;
    }
    
    // 提取关键词
    public  void ExtractKeywords(List<ChatData> chatDataList)
    {
        var tfidfExtractor = new JiebaNet.Analyser.TfidfExtractor();
        foreach (var chatData in chatDataList)
        {
            var keywords = tfidfExtractor.ExtractTags(chatData.Content, 20, null);
            chatData.Keywords = string.Join("", keywords);
        }
    }
    
    // 获取前n个最常出现的词
    private static string GetMostCommonWords(IEnumerable<string> words, int n)
    {
        var counts = new Dictionary<string, int>();
        foreach (var word in words)
        {
            if (counts.TryGetValue(word, out var value))
            {
                counts[word] = ++value;
            }
            else
            {
                counts[word] = 1;
            }
        }
        // 使用空格分隔符，将每个词和出现次数合并成一个字符串
        var result = string.Join(" ", counts.OrderByDescending(kvp => kvp.Value).Take(n));

        return result;
    }
    
    // 处理聊天数据
    public  ChatProcessedData ProcessChatData(List<ChatData> chatDataList)
    {
        // 遍历读取用户名，找出两个用户
        var userNameList = chatDataList.Select(cd => cd.Username).Distinct().ToList();
        var user1Messages = chatDataList.Where(cd => cd.Username == userNameList[0]).ToList();
        var user2Messages = chatDataList.Where(cd => cd.Username == userNameList[1]).ToList();

        var totalChatCount = chatDataList.Count;
        
        var user1MessageCount = user1Messages.Count;
        var user2MessageCount = user2Messages.Count;
        // 把user1所有的消息List拼接成一个string，去除空格换行, 然后计算长度
        var user1WordCount = string.Join("", user1Messages.Select(cd => cd.Content).ToList()).Length;
        var user2WordCount = string.Join("", user2Messages.Select(cd => cd.Content).ToList()).Length;
        var totalWordCount = user1WordCount + user2WordCount;
        // 根据用户名读取用户1的关键词Keywords并合并成一个字符串
        var user1Keywords = string.Join("", user1Messages.Select(cd => cd.Keywords).ToList());
        var user2Keywords = string.Join("", user2Messages.Select(cd => cd.Keywords).ToList());
        var jieba = new JiebaSegmenter();
        var words1 = jieba.Cut(user1Keywords);
        var words2 = jieba.Cut(user2Keywords);
        // 根据关键词字符串提取出20个高频词及其频数，并存入ChatProcessedData
        var user1HighFrequencyWords = GetMostCommonWords(words1, 20);
        var user2HighFrequencyWords = GetMostCommonWords(words2, 20);
        
        _chatTimeReportService.createConverstionList(chatDataList);

        double user1AverageReplyTime = _chatTimeReportService.computeUserResponseTime(userNameList[0], 0);
        double user2AverageReplyTime = _chatTimeReportService.computeUserResponseTime(userNameList[1], 1);

        var user1ResponseTimeTimes = _chatTimeReportService.getMyResponseTimeTimes();
        var user2ResponseTimeTimes = _chatTimeReportService.getYourResponseTimeTimes();
        
        // 初始化情感统计相关变量
        var emotionReportService = new EmotionReportService(null);
        emotionReportService.AnalyzeEmotionData(chatDataList);
        
        return new ChatProcessedData
        {
            Username1 = userNameList[0],
            Username2 = userNameList[1],
            TotalChatCount = totalChatCount,
            TotalWordCount = totalWordCount,
            User1MessageCount = user1MessageCount,
            User2MessageCount = user2MessageCount,
            User1WordCount = user1WordCount,
            User2WordCount = user2WordCount,
            User1HighFrequencyWords = user1HighFrequencyWords,
            User2HighFrequencyWords = user2HighFrequencyWords,
            FirstChatTime = _chatTimeReportService.computeFirstChatTime(),
            LastChatTime = _chatTimeReportService.computeLastChatTime(),
            TotalDuration = _chatTimeReportService.computeTotalChatTime(),
            AverageDuration = _chatTimeReportService.computeAverageDuration(),
            AverageInterval = _chatTimeReportService.computeAverageInterval(),
            ConversationCount = _chatTimeReportService.computeConversationCount(),
            User1AverageReplyTime = user1AverageReplyTime,
            User2AverageReplyTime = user2AverageReplyTime,
            User1LessThanOneMinute = user1ResponseTimeTimes[0],
            User1LessThanFiveMinutes = user1ResponseTimeTimes[1],
            User1LessThanTenMinutes = user1ResponseTimeTimes[2],
            User1MoreThanTenMinutes = user1ResponseTimeTimes[3],
            User2LessThanOneMinute = user2ResponseTimeTimes[0],
            User2LessThanFiveMinutes = user2ResponseTimeTimes[1],
            User2LessThanTenMinutes = user2ResponseTimeTimes[2],
            User2MoreThanTenMinutes = user2ResponseTimeTimes[3],
            // 设置情感相关数据
            PositiveMessageCount = emotionReportService._emotionCounts["积极"],
            NeutralMessageCount = emotionReportService._emotionCounts["中性"],
            NegativeMessageCount = emotionReportService._emotionCounts["消极"],
            LoveMessageCount = emotionReportService._emotionCounts["喜爱"],
            HappyMessageCount = emotionReportService._emotionCounts["愉快"],
            NormalMessageCount = emotionReportService._emotionCounts["正常"],
            AngryMessageCount = emotionReportService._emotionCounts["愤怒"],
            DisgustMessageCount = emotionReportService._emotionCounts["厌恶"],
            FearMessageCount = emotionReportService._emotionCounts["恐惧"],
            SadMessageCount = emotionReportService._emotionCounts["悲伤"],

            User1PositiveMessageCount = emotionReportService._userEmotionCounts.ContainsKey(userNameList[0])? emotionReportService._userEmotionCounts[userNameList[0]]["积极"] : 0,
            User1NeutralMessageCount = emotionReportService._userEmotionCounts.ContainsKey(userNameList[0])? emotionReportService._userEmotionCounts[userNameList[0]]["中性"] : 0,
            User1NegativeMessageCount = emotionReportService._userEmotionCounts.ContainsKey(userNameList[0])? emotionReportService._userEmotionCounts[userNameList[0]]["消极"] : 0,
            User1LoveMessageCount = emotionReportService._userEmotionCounts.ContainsKey(userNameList[0])? emotionReportService._userEmotionCounts[userNameList[0]]["喜爱"] : 0,
            User1HappyMessageCount = emotionReportService._userEmotionCounts.ContainsKey(userNameList[0])? emotionReportService._userEmotionCounts[userNameList[0]]["愉快"] : 0,
            User1NormalMessageCount = emotionReportService._userEmotionCounts.ContainsKey(userNameList[0])? emotionReportService._userEmotionCounts[userNameList[0]]["正常"] : 0,
            User1AngryMessageCount = emotionReportService._userEmotionCounts.ContainsKey(userNameList[0])? emotionReportService._userEmotionCounts[userNameList[0]]["愤怒"] : 0,
            User1DisgustMessageCount = emotionReportService._userEmotionCounts.ContainsKey(userNameList[0])? emotionReportService._userEmotionCounts[userNameList[0]]["厌恶"] : 0,
            User1FearMessageCount = emotionReportService._userEmotionCounts.ContainsKey(userNameList[0])? emotionReportService._userEmotionCounts[userNameList[0]]["恐惧"] : 0,
            User1SadMessageCount = emotionReportService._userEmotionCounts.ContainsKey(userNameList[0])? emotionReportService._userEmotionCounts[userNameList[0]]["悲伤"] : 0,

            User2PositiveMessageCount = emotionReportService._userEmotionCounts.ContainsKey(userNameList[1])? emotionReportService._userEmotionCounts[userNameList[1]]["积极"] : 0,
            User2NeutralMessageCount = emotionReportService._userEmotionCounts.ContainsKey(userNameList[1])? emotionReportService._userEmotionCounts[userNameList[1]]["中性"] : 0,
            User2NegativeMessageCount = emotionReportService._userEmotionCounts.ContainsKey(userNameList[1])? emotionReportService._userEmotionCounts[userNameList[1]]["消极"] : 0,
            User2LoveMessageCount = emotionReportService._userEmotionCounts.ContainsKey(userNameList[1])? emotionReportService._userEmotionCounts[userNameList[1]]["喜爱"] : 0,
            User2HappyMessageCount = emotionReportService._userEmotionCounts.ContainsKey(userNameList[1])? emotionReportService._userEmotionCounts[userNameList[1]]["愉快"] : 0,
            User2NormalMessageCount = emotionReportService._userEmotionCounts.ContainsKey(userNameList[1])? emotionReportService._userEmotionCounts[userNameList[1]]["正常"] : 0,
            User2AngryMessageCount = emotionReportService._userEmotionCounts.ContainsKey(userNameList[1])? emotionReportService._userEmotionCounts[userNameList[1]]["愤怒"] : 0,
            User2DisgustMessageCount = emotionReportService._userEmotionCounts.ContainsKey(userNameList[1])? emotionReportService._userEmotionCounts[userNameList[1]]["厌恶"] : 0,
            User2FearMessageCount = emotionReportService._userEmotionCounts.ContainsKey(userNameList[1])? emotionReportService._userEmotionCounts[userNameList[1]]["恐惧"] : 0,
            User2SadMessageCount = emotionReportService._userEmotionCounts.ContainsKey(userNameList[1])? emotionReportService._userEmotionCounts[userNameList[1]]["悲伤"] : 0
            
        };
    }
    // 新的方法用于添加情感分析到ChatData列表中的每个ChatData对象
    public async Task AddEmotionalAnalysisToChatData(List<ChatData> chatDataList)
    {
        foreach (var chatData in chatDataList)
        {
            var analysisResult = await _emotionalAnalysisService.AnalyzeEmotionAsync(chatData.Content);
            chatData.Emotion = analysisResult.Emotion;
            chatData.EmotionTone = analysisResult.EmotionTone;
            chatData.EmotionScore = analysisResult.EmotionScore;
            await Task.Delay(500); 
        }
    }
}



// 下面是聊天记录的示例，请复制并粘贴到控制台以进行测试。（也可以在qq聊天界面按Alt+A，全选复制聊天记录）
/*


岩浆来咯 2024/3/26 13:29:55


岩浆来咯 2024/3/26 13:30:26


岩浆来咯 2024/4/24 0:03:29


岩浆来咯 2024/5/3 11:31:24


小明 2024/5/13 13:24:49
链接：https://pan.baidu.com/s/1N7zFNuQswZO-6YR1gY-f-g?pwd=4wl7  
提取码：4wl7

小明 2024/5/20 18:30:45
[糸的聊天记录]

岩浆来咯 2024/7/9 16:38:20


对方已成功接收了你发送的离线文件“3.png”(168.04KB)。


岩浆来咯 2024/12/2 23:04:48
123
123

岩浆来咯 2024/12/2 23:08:19


1 

小明 2024/12/3 11:08:38
1

岩浆来咯 2024/12/3 11:08:41
2

小明 2024/12/3 11:08:43
3

岩浆来咯 2024/12/3 11:08:44
4

小明 2024/12/3 11:08:45
5

岩浆来咯 2024/12/3 11:08:46
6

小明 2024/12/3 11:08:48
7

岩浆来咯 2024/12/3 11:08:49
8

小明 2024/12/3 11:08:52
9

岩浆来咯 2024/12/3 11:08:53
10


*/